package com.cwt_taxi_xa.util;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.protocol.DeviceBiz;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
    /**
     * 压缩文件和文件夹（SDCard文件压缩）
     * http://www.manongjc.com/article/4206.html
     *
     * @param srcFile 要压缩的文件或文件夹
     */
    public static void ZipFolder(File srcFile) {
        File zipFile = null;
        try {
             zipFile = new File(Constants.LOG_PATH_ZIP + "_" + SPUtils.getParamString("SPK_clientcode","") + "_" + DeviceBiz.getCarNumberSingleLetter()+ "_"+  new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(new Date()) + ".zip");
            if (zipFile.exists()){
                zipFile.delete();
                zipFile.createNewFile();
            }
            //创建ZIP
            ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFile));
            //压缩
            ZipFiles(srcFile.getParent() + File.separator, srcFile.getName(), outZip);
            //完成和关闭
            outZip.finish();
            outZip.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            CatchLogUtils.startLog();
            if (zipFile != null){
                FTPUtils.upLoadFile(zipFile);
            }
        }

    }

    /**
     * 压缩文件
     *
     * @param srcFileParentName
     * @param srcFileName
     * @param zipOutputSteam
     */
    private static void ZipFiles(String srcFileParentName, String srcFileName, ZipOutputStream zipOutputSteam) throws Exception {
        if (zipOutputSteam == null)
            return;
        File file = new File(srcFileParentName + srcFileName);

        if (file.isFile()) {
            ZipEntry zipEntry = new ZipEntry(srcFileName);
            FileInputStream inputStream = new FileInputStream(file);
            zipOutputSteam.putNextEntry(zipEntry);
            int len;
            byte[] buffer = new byte[1024 * 1024 * 10]; //10M
            while ((len = inputStream.read(buffer)) != -1) {
                zipOutputSteam.write(buffer, 0, len);
            }
            zipOutputSteam.closeEntry();
        } else {
            //文件夹
            String fileList[] = file.list();
            //没有子文件和压缩
            if (fileList.length <= 0) {
                ZipEntry zipEntry = new ZipEntry(srcFileName + File.separator);
                zipOutputSteam.putNextEntry(zipEntry);
                zipOutputSteam.closeEntry();
            }
            //子文件和递归
            for (int i = 0; i < fileList.length; i++) {
                ZipFiles(srcFileParentName + srcFileName + "/", fileList[i], zipOutputSteam);
            }
        }
    }
}
